#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/3/1 16:40
# @Author  : lirang
# @Site    :
# @File    : mySocketServer.py
# @Software: PyCharm

import os
import json
import time
import threading
import SocketServer

#获取文件头信息
def take_hander(file_path, code = "utf-8"):
    file_name_list = file_path.rsplit(os.sep, 1)
    if len(file_name_list) > 1:
        file_name = file_name_list[1]
    else:
        file_name = file_path
    file_size = os.path.getsize(file_path)
    file_type = file_name.split('.')[1]
    date = time.strftime("%Y-%m-%D %H:%M:%S", time.localtime())
    head_data = {
        "file_name":file_name,
        "file_size":file_size,
        "file_type":file_type,
        "date":date,
        "charset":code
    }
    file_header = json.dumps(head_data)
    return file_header

path = "rkl.txt"
class Myhandler(SocketServer.BaseRequestHandler):
    def setup(self):
        #self.file = file(path, "r")
        #self.content = self.file.read()
        self.file_header = take_hander(path)
    def handle(self):
        print ("%s:%s is connected"%self.client_address)
        request_data = self.request.recv(512)
        print request_data
        self.request.sendall(self.file_header)
        #self.request.sendall(self.content)
        self.file = file(path, "r")
        i = 0
        #分片发送文件数据
        while 1:
            filedata = self.file.read(10240)
            if not filedata:
                break
            self.request.sendall(filedata)
            print "i:%d,length:%d"%(i,len(filedata))
            i = i + 1
    def finish(self):
        print "file send done"
        if self.file.closed == False:
            self.file.close()

class Myserver(SocketServer.TCPServer, SocketServer.ThreadingMixIn):
    pass

m = Myserver(("10.78.1.100",8000),Myhandler)
th = threading.Thread(target=m.serve_forever(),args=())
th.start()

m.shutdown()
m.server_close()

